
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import java.io.*;
import java.applet.AppletContext.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import javax.swing.event.*;

import java.lang.reflect.*;

import javax.swing.border.*;
import javax.swing.plaf.basic.*;

import  java.awt.image.ImageConsumer ;
import java.awt.image.ImageObserver;
import   java.applet.AudioClip;

import javax.swing.filechooser.FileView;

import java.net.*;


public class Library extends JFrame
{
	int find;
	JSplitPane span;
	JPanel leftPan, rightPan, totListPan, menuPan,listPan1,listPan2, buttonPan,detailPan,imgPanel, radioPanel;
	JButton bookButt, customButt, delButt, previewButt, imgButt;
	JList leftList, rightList;
	DefaultListModel leftModel, rightModel;
	JLabel alertLabel,leftLabel,rightLabel,imgPDFLabel,pubRegiLabel, issueBookLabel,returnLabel;
	Container contentPane;
	JFrame frame;
	FileReader reader;////not gui essential
	JProgressBar progress1;////not gui essential 
	JTextField readersTextField, searchInputField;
	JRadioButton bookRadio, customerRadio;
	ButtonGroup radioGroup;//in place of popup menu which took me three hours before I finally decided that a popup menu on left click was not going to happen
	private JButton btnViewAll;
	private JButton btnSignOut;
	private JPanel panel;//displays appropo button, dependent on radio buttons
	private JRadioButton rdbtnBooks;
	private JRadioButton rdbtnCustomers;
	private JLabel lblReturnPurchDate;
	private JLabel lblCustomerReturnBook;
	private JLabel lblOtherDetails;
	private JButton btnSearch;
	private JButton btnAdd;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private boolean isCust = false;
	
	/**
	 * NEW SQLAPI
	 * */
	private sqlAPI look = new sqlAPI(); // interfaces w/ books
	
	
	Library()
	{
		super("Library Management");

		contentPane=getContentPane();
		contentPane.setLayout(new BorderLayout()); 

		
		span=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT){
			private final int location = 250;
			{
				setDividerLocation( location );
			}
			@Override
			public int getDividerLocation() {
				return location ;
			}
			@Override
			public int getLastDividerLocation() {
				return location ;
			}
		};

		leftPan=new JPanel();
		leftPan.setLayout(new BorderLayout());
		rightPan=new JPanel();
		rightPan.setLayout(new BorderLayout());
		span.setLeftComponent(leftPan);
		span.setRightComponent(rightPan);

		menuPan=new JPanel();
		menuPan.setBackground(new Color(0, 128, 128));
		menuPan.setLayout(new GridLayout(4,1));

		bookButt=new JButton("Books");
		bookButt.setBackground(new Color(0, 128, 128));
		customButt=new JButton("Customers");
		customButt.setBackground(new Color(0, 128, 128));
		alertLabel=new JLabel("Click Book or Customer to edit.");
		alertLabel.setForeground(new Color(25, 25, 112));
		alertLabel.setBackground(new Color(143, 188, 143));

		otherButtonsListener buttonListener=new otherButtonsListener();
		btnViewAll = new JButton("View All");
		btnViewAll.setBackground(new Color(0, 128, 128));
		btnViewAll.addActionListener(buttonListener);
		menuPan.add(btnViewAll);

		btnSignOut = new JButton("Sign Out");
		btnSignOut.setBackground(new Color(0, 128, 128));
		btnSignOut.addActionListener(buttonListener);
		menuPan.add(btnSignOut);

		radioPanel=new JPanel();
		radioPanel.setBackground(new Color(143, 188, 143));

		menuPan.add(radioPanel);

		radioListener listeningtotheRadio=new radioListener();
		rdbtnBooks = new JRadioButton("Books");

		rdbtnBooks.addActionListener(listeningtotheRadio);
		buttonGroup.add(rdbtnBooks);
		rdbtnBooks.setBackground(new Color(143, 188, 143));
		radioPanel.add(rdbtnBooks);

		rdbtnCustomers = new JRadioButton("Customers");
		rdbtnCustomers.addActionListener(listeningtotheRadio);
		buttonGroup.add(rdbtnCustomers);
		rdbtnCustomers.setBackground(new Color(143, 188, 143));
		rdbtnCustomers.setForeground(new Color(0, 0, 0));
		radioPanel.add(rdbtnCustomers);
		menuPan.add(alertLabel);

		leftPan.add(menuPan,BorderLayout.NORTH);

		totListPan=new JPanel();
		totListPan.setLayout(new GridLayout(1,2));

		listPan1=new JPanel();
		listPan1.setLayout(new BorderLayout());
		listPan2=new JPanel();
		listPan2.setLayout(new BorderLayout());

		leftLabel=new JLabel();
		leftLabel.setBackground(new Color(210, 180, 140));
		rightLabel=new JLabel();
		rightLabel.setBackground(new Color(210, 180, 140));

		leftModel=new DefaultListModel();
		rightModel=new DefaultListModel();
		leftList=new JList(leftModel);
		leftList.setBackground(new Color(143, 188, 143));
		rightList=new JList(rightModel);
		rightList.setBackground(new Color(95, 158, 160));

		listPan1.add(leftLabel,BorderLayout.NORTH);
		listPan1.add(leftList, BorderLayout.CENTER); 
		listPan2.add(rightLabel,BorderLayout.NORTH);
		listPan2.add(rightList,BorderLayout.CENTER);

		totListPan.add(listPan1);
		totListPan.add(listPan2);
		leftPan.add(totListPan,BorderLayout.CENTER);

		buttonPan=new JPanel();
		buttonPan.setBackground(new Color(0, 128, 128));
		buttonPan.setLayout(new FlowLayout());


		deleteButtonListener delListener=new deleteButtonListener();

		delButt=new JButton("Delete This Book");
		delButt.setBackground(new Color(0, 128, 128));
		delButt.addActionListener(delListener);

		/*previewButt=new JButton("Upload PDF");
		previewButt.setBackground(new Color(0, 128, 128));
		previewButt.addActionListener(buttonListener);

		imgButt=new JButton("Upload Cover Image");
		imgButt.setBackground(new Color(0, 128, 128));
		imgButt.addActionListener(buttonListener);
		*/
		buttonPan.add(delButt);
		
		//buttonPan.add(previewButt);
		//buttonPan.add(imgButt);

		rightPan.add(buttonPan,BorderLayout.SOUTH);

		imgPDFLabel= new JLabel();
		imgPDFLabel.setBackground(new Color(0, 128, 128));
		returnLabel=new JLabel("Return Date:         ");

		imgPanel=new JPanel();
		imgPanel.setBackground(new Color(143, 188, 143));
		imgPanel.setLayout(new BorderLayout());

		detailPan=new JPanel();
		detailPan.setBackground(new Color(143, 188, 143));
		detailPan.setLayout(new FlowLayout());
		pubRegiLabel= new JLabel("Publication:        ");
		detailPan.add(pubRegiLabel);
		issueBookLabel=new JLabel("Issue:        ");
		detailPan.add(issueBookLabel);

		lblReturnPurchDate = new JLabel("Return Date:        ");
		detailPan.add(lblReturnPurchDate);
		imgPanel.add(detailPan,BorderLayout.SOUTH);

		lblCustomerReturnBook = new JLabel("Customer:        ");
		detailPan.add(lblCustomerReturnBook);

		lblOtherDetails = new JLabel("Other Details:          ");
		detailPan.add(lblOtherDetails);
		imgPanel.add(imgPDFLabel,BorderLayout.CENTER);

		rightPan.add(imgPanel,BorderLayout.CENTER);

		panel = new JPanel();
		panel.setBackground(new Color(0, 128, 128));
		imgPanel.add(panel, BorderLayout.NORTH);

		btnAdd = new JButton("Add a Book");
		btnAdd.setBackground(new Color(0, 128, 128));
		addButtonListener addListen=new addButtonListener();
		btnAdd.addActionListener(addListen);
		panel.add(btnAdd);

		btnSearch = new JButton("Search Books");
		btnSearch.setBackground(new Color(0, 128, 128));
		searchButtonListener searchListen=new searchButtonListener();
		btnSearch.addActionListener(searchListen);
		panel.add(btnSearch);

		contentPane.add(span);
		progress1=new JProgressBar();
		
/**-----------------------------------------------------------------------------------------------------------------------
 * 						Populate the Current library inventory 
 *-----------------------------------------------------------------------------------------------------------------------*/		
		try{
			popBookList();
		}catch(Exception der){ 
			alertLabel.setText("263:Error Occurs: \n"+der);
            System.out.println("adding all books failed problem");
            der.printStackTrace();
		}
	}
/*------------------------------------------------------------------------------------------------------------------------
 * begin listening!!  WE ARE LISTENING!! YEAH!!!!
 ------------------------------------------------------------------------------------------------------------------------*/
	private class listListener implements ListSelectionListener//triggers when something in leftList is selected
	{
		public void valueChanged(ListSelectionEvent arg0) 
		{//when book in list is selected, in right panel book cover and option to check the book out or in made available
			String selectionL=leftList.getSelectedValue().toString();//selection is the name of the book the user has selected
			String selectionR=rightList.getSelectedValue().toString();
			int j;
			if(isCust)
			{
					try{
						ResultSet allCust = look.getAllUsers();
						ResultSet uHist = look.getUserHistory(allCust.getInt("user_id"));
						uHist.next();
						ResultSet allBooks = look.getAllBooks();
						if(arg0.getSource() == rightList){
							j = rightList.getSelectedIndex();
							leftList.setSelectedIndex(j);
						}
						else{
							j = leftList.getSelectedIndex();
							rightList.setSelectedIndex(j);
						}
						allCust.absolute(j+1);
						String regDate = allCust.getString("date_created");
						int bookID = uHist.getInt("bookID");
						String bookName = (look.getBook(bookID)).getString("title");
						String status = "Available";
						if((look.getBook(bookID)).getBoolean("checkedOut")){
							status = "Checked Out";
						}
//---------------------------------------------------------------------------------------
//              Trigger labels to show publication info, etc
//---------------------------------------------------------------------------------------
						pubRegiLabel.setText("Registration: "+regDate);
						issueBookLabel.setText("Book: "+bookName); //issue information from selected book;
						lblReturnPurchDate.setText("");
						lblOtherDetails.setText("");
						lblCustomerReturnBook.setText("Status: "+status);
						previewButt.setVisible(false);
						imgButt.setVisible(false);
					}
					catch(Exception e){
						e.printStackTrace();
					}
				
			}
			else
			{
				ResultSet allBooks = look.getAllBooks();
				try{
					if(arg0.getSource() == rightList){
						j = rightList.getSelectedIndex();
						leftList.setSelectedIndex(j);
					}
					else{
						j = leftList.getSelectedIndex();
						rightList.setSelectedIndex(j);
					}
					String pub = allBooks.getString("publisher");
					String issue = allBooks.getString("issue_date");
					String status = "Checked Out";// set to checked out by default
//---------------------------------------------------------------------------------------
//	              Trigger labels to show publication info, etc
//---------------------------------------------------------------------------------------
					pubRegiLabel.setText("Publication: "+pub);
					issueBookLabel.setText("Issue: "+issue); //issue information from selected book;
					lblReturnPurchDate.setText("");
					lblOtherDetails.setText("");
					lblCustomerReturnBook.setText("Status: "+status);
					previewButt.setVisible(true);
					imgButt.setVisible(true);
					previewButt.setEnabled(true);
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
			delButt.setEnabled(true);
		}
	}
	private class otherButtonsListener implements ActionListener//for signout and backup and book only thing...do we do check in too??
	{
		public void actionPerformed(ActionEvent event)
		{
			Object source=event.getSource();
			if(source==btnSignOut)
			{
				setVisible(false);
				removeAll();
				splash1 s = new splash1();
				s.setVisible(true);
				s.setSize(270,180);
				s.setLocation(120,100);
			}
			if(source==btnViewAll)
			{
				if(isCust){
					popCustList();
				}
				else{
					popBookList();
				}
			}
			if(source==imgButt)
			{
				String selectionL=leftList.getSelectedValue().toString();
				String selectionR=rightList.getSelectedValue().toString();
				//upload image
			}
			if(source==previewButt)
			{
				String selectionL=leftList.getSelectedValue().toString();
				String selectionR=rightList.getSelectedValue().toString();
				//upload pdf
			}

		}
	}
	private class deleteButtonListener implements ActionListener
	{
		public void actionPerformed(ActionEvent event)
		{
			System.out.println("DeleteHere-1");				
			
			String selectionL=leftList.getSelectedValue().toString();
			String selectionR=rightList.getSelectedValue().toString();
			System.out.println("SelL:" + selectionL + "SelR:" + selectionR);
			if(isCust==true)
			{
				//delete selected person
				ResultSet allCust= look.getAllUsers();
				try {
					while (allCust.next()) {
						if ( allCust.getInt("user_id") == Integer.parseInt(selectionL) ) {
							look.deleteBook(Integer.parseInt(selectionL));
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				delButt.enable(false);
				popCustList();
				JOptionPane.showMessageDialog(frame, "User with ID " + selectionL + " deleted.");
				delButt.enable(true);
			}
			else
			{
				System.out.println("DeleteHere0");
				//delete selected book, but that would be sad, books are indispensable.
				//String selectionL=leftList.getSelectedValue().toString();
				//String selectionR=rightList.getSelectedValue().toString();
				//also I just realized it probably wouldn't matter whether or not the selected thing is book or customer.
				System.out.println("DeleteHere1");
				ResultSet allBooks = look.getAllBooks();
				System.out.println("DeleteHere2");
				try {
					while (allBooks.next()) {
						String cTitle = allBooks.getString("title");
						System.out.println(cTitle);
						if ( (allBooks.getString("title")).equals(selectionL) ) {
							look.deleteBook(allBooks.getInt("book_id"));
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				delButt.enable(false);
				JOptionPane.showMessageDialog(frame, "Book with Title " + selectionL + " deleted.");
				popBookList();
				delButt.enable(true);
			}
		}
	}
	private class searchButtonListener implements ActionListener
	{
		public void actionPerformed(ActionEvent event)
		{
			if(isCust)
			{
				String want=(String)JOptionPane.showInputDialog("Enter ID of customer");
				if(want==null)
				{
					//do nothing! user hit x or canceled input dialog. That is totes ok.
				}
				else
				{

					if(!want.equals(""))
					{
						leftModel.removeAllElements();
						rightModel.removeAllElements();
						//populate lists with found customers
						//if none found alertLabel.setText("nobody found");
					}
					else
						alertLabel.setText("You failed to enter any text");//will make custom dialog box if enough time
				}


			}
			else
			{
				//tghsethau!!!graaaah choice between title/author search + input field
				//I need to make a custom dialog for this one then T.T
				//...or I can make TWO dialog boxes XD
				Object[] options = {"Title Search", "Author Search"};
				int n = JOptionPane.showOptionDialog(frame, "Pick", "We know your secret",JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE,
						null,
						options,
						options[0]);
				if(n==0)//they clicked title search
				{
					String want=(String)JOptionPane.showInputDialog("Enter Title of Book");
					if(want==null)
					{
						//do nothing! user hit x or canceled input dialog. That is totes ok.
					}
					else
					{

						if(!want.equals(""))
						{
							leftModel.removeAllElements();
							rightModel.removeAllElements();
							//populate lists with found customers
							//if none found alertLabel.setText("nobody found");
						}
						else
							alertLabel.setText("You failed to enter any text");//will make custom dialog box if enough time
					}

				}
				else if(n==1)//they clicked author search
				{
					String want=(String)JOptionPane.showInputDialog("Enter Name of Author");
					if(want==null)
					{
						//do nothing! user hit x or canceled input dialog. That is totes ok.
					}
					else
					{


						if(!want.equals(""))
						{
							leftModel.removeAllElements();
							rightModel.removeAllElements();
							//populate lists with found customers
							//if none found alertLabel.setText("nobody found");
						}
						else
							alertLabel.setText("You failed to enter any text");//will make custom dialog box if enough time
					}

				}
				if(n==2||n==3)
				{
					//they clicked cancel or exited
				}

			}
		}
	}
	private class addButtonListener implements ActionListener
	{
		public void actionPerformed(ActionEvent event)
		{
			if(isCust==true)
			{
				Addcust a =new Addcust();
				popCustList();
			}
			else
			{
				ImageUploader b = new ImageUploader();
				popBookList();
			}
		}
	}
	private class radioListener implements ActionListener//listener for radio buttons
	{
		public void actionPerformed(ActionEvent event)
		{
			Object source=event.getSource();
			if(source.equals(rdbtnBooks))
			{
				isCust=false;//buttons do book things now. for example, btnAdd should trigger the add book thing
				
				popBookList();

				leftLabel.setText("Title");
				rightLabel.setText("Author");

				pubRegiLabel.setText("Publication: ");
				issueBookLabel.setText("Issue: ");
				lblReturnPurchDate.setText("Return: ");
				lblCustomerReturnBook.setText("Customer: ");

				btnAdd.setText("Add a Book");
				btnSearch.setText("Search Books");
				delButt.setText("Delete This Book");
			}
			if(source.equals(rdbtnCustomers))
			{
				isCust=true;//buttons do customer things now, for example btnAdd should trigger the add customer thing

				popCustList();
				
				leftLabel.setText("ID");
				rightLabel.setText("Customer Name");

				pubRegiLabel.setText("Registration Date: ");
				issueBookLabel.setText("Book: ");
				lblReturnPurchDate.setText("Purchased: ");
				lblCustomerReturnBook.setText("Return: ");

				btnAdd.setText("Add a Customer");
				btnSearch.setText("Search Customers");
				delButt.setText("Delete This Person");
			}

		}
	}
	public void popBookList()//method for populating the list
	{
		try//populate Lists with all books and associated authors(bookList and authList).
		{
			leftModel.clear();
			rightModel.clear();
			ResultSet allBooks =  look.getAllBooks(); // new table with all the books
			allBooks.absolute(1);// sets to the start of the rs
			String bookNameX = "";
			String authNameX = "";
			int i = -1;

			// While loop checks the position of the resultset row int
			// and breaks as soon as we hit the last item in the table
			while(!allBooks.isAfterLast()){
				i = allBooks.getRow();
				// get dat book!
				bookNameX = allBooks.getString("title");
				leftModel.addElement(bookNameX);
				// love dat auth...or!
				authNameX = allBooks.getString("author_last_name");
				rightModel.addElement(authNameX);
				allBooks.next();// itterate to the next book
			}
//			allBooks.close();
		}
		catch(Exception der){
			alertLabel.setText("553:Error Occurs: \n"+der);
			System.out.println("adding all books failed problem");
			der.printStackTrace();
		}
	}
	public void popCustList()//method for populating the list
	{
		try//populate Lists with all customers and.
		{
			leftModel.clear();
			rightModel.clear();
			ResultSet allCust =  look.getAllUsers(); // new table with all the books
			allCust.absolute(1);// sets to the start of the rs
			String custNameX = "";
			String idX = "";
			int i = -1;

			// While loop checks the position of the resultset row int
			// and breaks as soon as we hit the last item in the table
			while(!allCust.isAfterLast()){
				i = allCust.getRow();
				// get dat cust!
				custNameX = allCust.getString("last_name");
				rightModel.addElement(custNameX);
				// love dat auth...or!
				idX = allCust.getString("user_id");
				leftModel.addElement(idX);
				allCust.next();// itterate to the next book
			}
//			allCust.close();
		}
		catch(Exception der){
			alertLabel.setText("583:Error Occurs: \n"+der);
			System.out.println("adding all books failed problem");
			der.printStackTrace();
		}
	}
	public static void main (String args[])
	{
		//Library lb=new Library();
		splash1 s=new splash1();

		s.setVisible(true);
		s.setSize(270,180);
		s.setLocation(120,100);
		//lb.setVisible(true);
		//lb.setSize(800,600);
	}    

}


